package problems

import (
	"fmt"
	"math"
	"strconv"
)

// BalancedStringSplit 1221
// https://leetcode-cn.com/problems/split-a-string-in-balanced-strings/
func BalancedStringSplit(s string) int {
	var res, num = 0, 0
	for k, v := range s {
		if v == 'L' {
			num++
		} else {
			num--
		}
		if num == 0 && k != 0 {
			res++
		}
	}
	return res
}

// OddCells 1252
// https://leetcode.cn/problems/cells-with-odd-values-in-a-matrix/
func OddCells(m int, n int, indices [][]int) int {
	num, ms, ns := 0, make([]int, m), make([]int, n)

	for _, v := range indices {
		ms[v[0]]++
		ns[v[1]]++
	}

	for _, i := range ms {
		for _, j := range ns {
			num += (i + j) % 2
		}
	}

	return num
}

// MinTimeToVisitAllPoints 1266
// https://leetcode-cn.com/problems/minimum-time-visiting-all-points/
func MinTimeToVisitAllPoints(points [][]int) int {
	var step = 0
	for i := 1; i < len(points); i++ {
		var x, y = math.Abs(float64(points[i][0] - points[i-1][0])), math.Abs(float64(points[i][1] - points[i-1][1]))
		if x > y {
			x, y = y, x
		}
		step += int(x) + int(y-x)
	}
	return step
}

// SubtractProductAndSum 1281
// https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
func SubtractProductAndSum(n int) int {
	var product, sum = 1, 0
	for n > 0 {
		product *= n % 10
		sum += n % 10
		n /= 10
	}
	return product - sum
}

// GetDecimalValue 1290
// https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer/
func GetDecimalValue(head *ListNode) int {
	var res = 0
	for head != nil {
		res, head = res*2+head.Val, head.Next
	}
	return res
}

// FindNumbers 1295
// https://leetcode-cn.com/problems/find-numbers-with-even-number-of-digits/
func FindNumbers(nums []int) int {
	var res = 0
	for _, v := range nums {
		if len(strconv.Itoa(v))%2 == 0 {
			res++
		}
	}
	return res
}

// ReplaceElements 1299
// https://leetcode-cn.com/problems/replace-elements-with-greatest-element-on-right-side/
func ReplaceElements(arr []int) []int {
	var max = 0
	for i := len(arr) - 1; i >= 0; i-- {
		if i == len(arr)-1 {
			arr[i], max = -1, arr[i]
		} else {
			if max < arr[i] {
				arr[i], max = max, arr[i]
			} else {
				arr[i] = max
			}
		}
		fmt.Println(i, max)
	}
	return arr
}
